package com.woniu.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.common.constant.RedisKeyConstant;
import com.woniu.common.entity.Result;
import com.woniu.common.entity.ResultCode;
import com.woniu.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
//GlobalFilter全局过滤器接口、Ordered执行顺序
public class LoginFilter implements GlobalFilter, Ordered {
    //定义常量
    private static final String WHITE_PATH = "/user/login, /address/list, /user/register, /alipay/return_url, /alipay/notify_url";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求头
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest server = exchange.getRequest();
        //获取请求路径
        String path = server.getURI().getPath();
        log.debug("请求路径为：{}", path);
        //检测该请求地址是否是白名单，如果是白名单就放行
        if (WHITE_PATH.contains(path)) {
            return chain.filter(exchange);
        }
        //获取请求头中的token
        String token = server.getHeaders().getFirst("token");
        //首先判断是否存在token,如果为空说明是一个非法请求
        if (StringUtils.isEmpty(token)) {
            Result result = Result.error(ResultCode.TOKEN_ERROR.getCode(), ResultCode.TOKEN_ERROR.getMessage());
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBufferFactory bufferFactory = response.bufferFactory();
            ObjectMapper objectMapper = new ObjectMapper();
            DataBuffer wrap = bufferFactory.wrap(objectMapper.writeValueAsBytes(result));
            return response.writeWith(Mono.fromSupplier(() -> wrap));
        }
        //解析token，获取手机号码，如果解析失败：1、token被慕该了 2.token过期了
        String mobile = "";
        try {
            Claims claims = JwtUtil.parseJWT(token);
            mobile = (String) claims.get("mobile");
        } catch (Exception exception) {
            exception.printStackTrace();
            Result result = Result.error(ResultCode.TOKEN_ERROR.getCode(), ResultCode.TOKEN_ERROR.getMessage());
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBufferFactory bufferFactory = response.bufferFactory();
            ObjectMapper objectMapper = new ObjectMapper();
            DataBuffer wrap = bufferFactory.wrap(objectMapper.writeValueAsBytes(result));
            return response.writeWith(Mono.fromSupplier(() -> wrap));
        }
        Boolean flag = stringRedisTemplate.hasKey(RedisKeyConstant.LOGIN_TOKEN + mobile);
        if (!flag) {
            Result result = Result.error(ResultCode.TOKEN_ERROR.getCode(), ResultCode.TOKEN_ERROR.getMessage());
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBufferFactory bufferFactory = response.bufferFactory();
            ObjectMapper objectMapper = new ObjectMapper();
            DataBuffer wrap = bufferFactory.wrap(objectMapper.writeValueAsBytes(result));
            return response.writeWith(Mono.fromSupplier(() -> wrap));
        }
        //判断redis中是否存在token
        //String redisToken = stringRedisTemplate.opsForValue().get("login" + token);
        //续签token（修改redis中的过期时间 token本身的过期时间没有改——不设置过期时间或者双token）
        stringRedisTemplate.expire("login:" + token, 60 * 30, TimeUnit.SECONDS);
        //存在就放行
        return chain.filter(exchange);
    }

    //过滤器的试行顺序，放回越小，排名越靠前执行优先级越高
    @Override
    public int getOrder() {
        return 5;
    }
}
